#include "dynamiccurvedisplayinterface.h"
#include "ui_dynamiccurvedisplayinterface.h"
#include<QPushButton>
Q_GLOBAL_STATIC(DynamicCurveDisplayInterface,theInstance);
const QColor lineColors[5] = {
    Qt::red,     // 温度
    Qt::blue,    // 湿度
    Qt::yellow,  // 光照
    Qt::green,   // CO2
    Qt::magenta  // 土壤湿度
};
int DynamicCurveDisplayInterface:: locationCount=0;
DynamicCurveDisplayInterface::DynamicCurveDisplayInterface(QWidget *parent) :
    QMainWindow(parent),
    ui(new Ui::DynamicCurveDisplayInterface)
{
    ui->setupUi(this);
    this->setWindowTitle("动态曲线界面");
    this->setWindowIcon(QIcon(":res/res/DynamicCurve.ico"));
    setupModel();
    setupChart();
//     定时器配置（每1秒更新）
  //  dataTimer = new QTimer(this);
  //  connect(dataTimer, &QTimer::timeout, this, &DynamicCurveDisplayInterface::readyUpdateChartData);
  //  dataTimer->start(1000);
//    QtimerDisplayCurve();
 connect(ModBusManger::instance(), &ModBusManger::sendDynamicCurve, this, &DynamicCurveDisplayInterface::readyUpdateChartData);

}

DynamicCurveDisplayInterface::~DynamicCurveDisplayInterface()
{
    delete ui;
}

void DynamicCurveDisplayInterface::updateChartData()
{

    // 获取时间范围
    QDateTime currentTime = QDateTime::currentDateTime();
  //  QDateTime startTime2 = currentTime.addDays(-5);

    QDateTime startTime = currentTime.addSecs(-SHOW_SECONDS);
//    QDateTime endTime = currentTime.addSecs();
    //int id=1000;
    // 执行数据库查询


    QSqlQuery query(UserMysqlS::instance()->getDataBase());
    query.prepare(" SELECT Time,AirTemperature,AirHumidity,LightIntensity,CO2Concentration,SoilMoisture " " FROM sensordatastand " " WHERE Time BETWEEN ? AND ? " " ORDER BY Time ASC ");
    query.addBindValue(startTime.toString("yyyy-MM-dd HH:mm:ss"));
    query.addBindValue(currentTime.toString("yyyy-MM-dd HH:mm:ss"));

    if (!query.exec())
    {
        qDebug() << "查询失败:" << query.lastError().text();
        return;
    }

    // 清空旧数据QLineSeries *series[5];  // 5条曲线: 温度/湿度/光照/CO2/土壤湿度

if(series[0]->count()>10)//当大于10个点时
{

    for(int i=0;i<5;i++)
    {
        series[i]->clear();

    }

}

//if(series[0]->count()>10)
//{
//    for(int i=0;i<5;i++)
//    {
//        series[i]->remove(0,5);
//    }
//}
//        for(int i=0;i<5;i++)
//        {
//            series[i]->clear();

//        }

    // 处理查询结果
    int minValue = 0;
    int maxValue = 2000;

    while (query.next()) {
        QDateTime time = query.value(0).toDateTime();
        int AirTemperature = query.value(1).toInt();
        int AirHumidity = query.value(2).toInt();
        int LightIntensity = query.value(3).toInt();
        int CO2ConCentration = query.value(4).toInt();
        int SoilMoisture = query.value(5).toInt();


        // 更新数据系列

        series[0]->append(time.toMSecsSinceEpoch(),AirTemperature);
        series[1]->append(time.toMSecsSinceEpoch(),AirHumidity);
        series[2]->append(time.toMSecsSinceEpoch(),LightIntensity);
        series[3]->append(time.toMSecsSinceEpoch(),CO2ConCentration);
        series[4]->append(time.toMSecsSinceEpoch(),SoilMoisture);
//        qDebug()<<"hahahahahaha---------->";
//        m_tempSeries->append(time.toMSecsSinceEpoch(), temp);
//        m_humiSeries->append(time.toMSecsSinceEpoch(), humi);

        //        */ 记录极值
        if (AirTemperature < minValue) minValue = AirTemperature;
        if (AirHumidity < minValue) minValue = AirHumidity;
        if (LightIntensity < minValue) minValue = LightIntensity;
        if (CO2ConCentration < minValue) minValue = CO2ConCentration;
        if (SoilMoisture < minValue) minValue = SoilMoisture;
        if (AirTemperature> maxValue) maxValue = AirTemperature;
        if (AirHumidity> maxValue) maxValue = AirHumidity;
        if (LightIntensity> maxValue) maxValue = LightIntensity;
        if (CO2ConCentration > maxValue) maxValue = CO2ConCentration;
        if (SoilMoisture> maxValue) maxValue = SoilMoisture;



    }

    // 设置坐标轴范围
    if (minValue != 1000 && maxValue != -1000) {
        axisY->setRange(minValue * 0.95, maxValue * 1.05);
        axisX->setRange(startTime, currentTime);
    }
   isProcessing=false;

}

void DynamicCurveDisplayInterface::readyUpdateChartData()
{
//    if(!locationCount)
//    {
//        isProcessing=false;

//    }
//    else
//    {

//        isProcessing=true;
//    }

    if( !isProcessing)
    {
      isProcessing=true;
      //qDebug()<<"天无绝人之路！！！！左旭驰"<<endl;
      //isProcessing =false;
     timeOutTimer =new QTimer();
     updateChartData();


    }

}

void DynamicCurveDisplayInterface::updateChartDataS()
{
    extern QVector<sensorData> globalSensorData;
    int count=globalSensorData.count();
    qDebug()<<"66666******66666";
    if(count>0)
    {
        qDebug()<<"88888******88888";
        sensorData Data=globalSensorData[count-1];
        QDateTime time = QDateTime::fromString(Data.Time, "yyyy-MM-dd HH:mm:ss");
        series[0]->append(QPointF(time.toMSecsSinceEpoch(),Data.AirTemperature));
        series[1]->append(time.toMSecsSinceEpoch(),Data.AirHumidity);
        series[2]->append(time.toMSecsSinceEpoch(),Data.LightIntensity);
        series[3]->append(time.toMSecsSinceEpoch(),Data.CO2Concentration);
        series[4]->append(time.toMSecsSinceEpoch(),Data.SoilMoisture);




    }



















}
DynamicCurveDisplayInterface *DynamicCurveDisplayInterface::instance()
{
return theInstance;
}

void DynamicCurveDisplayInterface::setupModel()
{


    model = new QSqlTableModel(this,UserMysqlS::instance()->getDataBase());
    model->setTable("sensordatastand");
    model->setSort(0, Qt::DescendingOrder); // 按时间降序排序

    if (!model->select())
    {
        QMessageBox::critical(this, "错误", "加载数据失败: " + model->lastError().text());
    }





}

void DynamicCurveDisplayInterface::setupChart()
{

     chart = new QChart();
     chart->setTitle("温室传感器数据监控");
     //chart->setAnimationOptions(QChart::NoAnimation);

     // 初始化5条曲线
     const char* seriesNames[5] = {
         "空气温度 (°C)",
         "空气湿度 (%)",
         "光照强度 (Lux)",
         "CO2浓度 (ppm)",
         "土壤湿度 (%)"
     };

     for (int i = 0; i < 5; ++i)//设置曲线颜色
     {
         series[i] = new QLineSeries();
         series[i]->setName(seriesNames[i]);
         series[i]->setColor(lineColors[i]);
         chart->addSeries(series[i]);


     }

     // 配置时间轴（X轴）
//     axisX = new QDateTimeAxis();
//     axisX->setTitleText("时间");
//     axisX->setFormat("yyyy-MM-dd hh:mm:ss");
     axisX = new QDateTimeAxis();
     axisX->setTitleText("时间");
     axisX->setFormat("yyyy-MM-dd hh:mm:ss");
     axisX->setTickCount(10);
     chart->addAxis(axisX, Qt::AlignBottom);
     chart->setAnimationOptions(QChart::SeriesAnimations);
     // 配置数值轴（Y轴）
     axisY = new QValueAxis(this);
     axisY->setTitleText("数值范围");
     axisY->setRange(0, 2000); // 初始范围，后续自动调整
     axisY->setTickCount(20);
     chart->addAxis(axisY, Qt::AlignLeft);

     // 将曲线绑定坐标轴
     for (auto &s : series) {
         s->attachAxis(axisX);
         s->attachAxis(axisY);
     }

     // 显示图表
     //QChartView *chartView = new QChartView();
     ui->chartView->setChart(chart);
     ui->chartView->setRenderHint(QPainter::Antialiasing);
     ui->chartView->setRenderHint(QPainter::HighQualityAntialiasing);
//     setCentralWidget(ui->chartView);




}



void DynamicCurveDisplayInterface::QtimerDisplayCurve()
{
    QTimer::singleShot(0, this, &DynamicCurveDisplayInterface::updateChartDataS);
    dataTimer = new QTimer(this);
    connect(dataTimer, &QTimer::timeout, this,&DynamicCurveDisplayInterface:: updateChartDataS);
    dataTimer->start(1000); // 1秒间隔
}







void DynamicCurveDisplayInterface::on_pushButtonBack_clicked()
{
this->close();
extern bool DynamicCurveStatus;
DynamicCurveStatus=false;

}



